//
//  FCVehicleIolAndCurveController.m
//  ZhuKuang
//
//  Created by mafy on 17/7/12.
//  Copyright © 2017年 jjkj. All rights reserved.
//

#import "FCVehicleIolAndCurveController.h"
#import "FCCustomIolAndCurveButton.h"
#import "FCVehicleIolAndCurveOptionTableView.h"
#import "FCVehicleIolAndCurveDakePickerView.h"
#import "FCVehicleIolAndCurveModel.h"
#import "SZCalendarPicker.h"
#import "ChartsViewController.h"

@interface FCVehicleIolAndCurveController () <UIGestureRecognizerDelegate>

@property (nonatomic, strong) FCCustomIolAndCurveButton *areaBtn;//选择车辆部门
@property (nonatomic, strong) FCCustomIolAndCurveButton *vehicleBtn;//选择车辆
@property (nonatomic, strong) FCCustomIolAndCurveButton *dateBtn;//选择日期
@property (nonatomic, strong) FCCustomIolAndCurveButton *startBtn;//开始时间
@property (nonatomic, strong) FCCustomIolAndCurveButton *endBtn;//结束时间

//下拉选择框
@property (nonatomic, strong) UIView *selectedBackView;
@property (nonatomic, strong) FCVehicleIolAndCurveOptionTableView *optionsTableView;

//日期选择框
@property (nonatomic,strong) SZCalendarPicker *calenderPicker;

//时间选择框
@property (nonatomic, strong) FCVehicleIolAndCurveDakePickerView *datePickerView;

@property (nonatomic, strong) NSMutableArray *departListArray;//车辆部门
@property (nonatomic, strong) NSMutableArray *carIDListArray;//车辆ID


@property (nonatomic , copy) NSString * timeString;//时间
@property (nonatomic, copy) NSString *startStr;//开始时分
@property (nonatomic, copy) NSString *endStr;//结束时分
//请求参数
@property (nonatomic, copy) NSString *carID;//车辆主键
@property (nonatomic, copy) NSString *startTime;//开始时间
@property (nonatomic, copy) NSString *endTime;//开始时间

@end

@implementation FCVehicleIolAndCurveController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"车辆油耗与速度曲线";
    
    
    [self setUpSelectedOption];
    
    [self getCarShopList];
}

#pragma mark - 提交按钮监听
- (void)commitButtonClick:(UIButton *)sender{
    
    
    NSLog(@"%@",self.carID);
    NSLog(@"%@",[NSString stringWithFormat:@"%@ %@",self.timeString,self.startStr]);
    NSLog(@"%@",[NSString stringWithFormat:@"%@ %@",self.timeString,self.endStr]);
    
    NSString *time1 = [NSString stringWithFormat:@"%@ %@",self.timeString,self.startStr];
    NSString *time2 = [NSString stringWithFormat:@"%@ %@",self.timeString,self.endStr];
    
    NSDate *date1 = [CommClass dateFormatTimeStamp:time1 timeFormat:@"yyyy-MM-dd HH:mm"];
    NSDate *date2 = [CommClass dateFormatTimeStamp:time2 timeFormat:@"yyyy-MM-dd HH:mm"];
    if ([date2 compare:date1] == NSOrderedAscending) {
        
        [LZXHelper postMessageWithText:@"结束时间不能小于开始时间" View:self.view];
        
        return;
    }
    NSTimeInterval value = [date2 timeIntervalSinceDate:date1];
    //如果时间大于60分钟，60*60秒，则显示时间
    if (value > 60 * 60) {
        
        [LZXHelper postMessageWithText:@"时间间隔不能大于60分钟" View:self.view];
        
        return;
    }
    
    //曲线页面
    ChartsViewController *oilCurveVC = [[ChartsViewController alloc] init];
    oilCurveVC.startTime = time1;
    oilCurveVC.endTime = time2;
    oilCurveVC.carId = self.carID;
    oilCurveVC.curveType = 0;
    [self presentViewController:oilCurveVC animated:YES completion:nil];
}

#pragma mark - 取消按钮监听
- (void)cancelButtonClick:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 选择按钮监听
- (void)selectedButtonClick:(UIButton *)sender{
    
    if (sender.tag == 100) {
    
        [self showViewWithY:CGRectGetMaxY(sender.frame) andHeight:220 andTag:200];
        _optionsTableView.type = @"1";
        _optionsTableView.dataArray = self.departListArray;
    }
    else if (sender.tag == 101){
        
        [self showViewWithY:CGRectGetMaxY(sender.frame) andHeight:220 andTag:200];
        _optionsTableView.type = @"2";
        _optionsTableView.dataArray = self.carIDListArray;
    }
    else if (sender.tag == 102) {
        
        [self selectorDateButtonClick:sender];
    }
    else if (sender.tag == 103){
        
        [self.datePickerView setHidden:NO];
        
        self.datePickerView.tag = 500;
    }
    else if (sender.tag == 104){
        
        [self.datePickerView setHidden:NO];
        
        self.datePickerView.tag = 501;
    }
}

#pragma mark - 数据请求
//车间
- (void)getCarShopList{
    
    [ClientRequest SOAPMthod:@"getcarShopList" soapBody:nil success:^(id responseObject) {
        
        for (NSDictionary *info in responseObject[@"carShopList"]) {
            
            FCVehicleIolAndCurveModel *model = [FCVehicleIolAndCurveModel mj_objectWithKeyValues:info];
            
            [self.departListArray addObject:model];
        }
        
        if (self.departListArray.count > 4) {//默认调用第一个的部门车辆信息
            
            FCVehicleIolAndCurveModel *model = self.departListArray[3];
            
            [self getCarByDepartID:model.carShopId];
            [self.areaBtn setTitle:model.name forState:UIControlStateNormal];
        }
        
    } failure:^(NSError *error) {
        
    }];
}

//获取部门车俩集合
- (void)getCarByDepartID:(NSString *)departID{
    
    NSDictionary *params = @{
                             
                             @"DepartID" : departID
                             
                             };
    
    [ClientRequest SOAPMthod:@"getCarByDepartID" soapBody:params success:^(id responseObject) {
        
        for (NSDictionary *info in responseObject[@"CarList"]) {
            
            FCVehicleIolAndCurveModel *model = [FCVehicleIolAndCurveModel mj_objectWithKeyValues:info];
            
            [self.carIDListArray addObject:model];
        }
        
        if (self.carIDListArray.count > 0) {//默认调用第一个的车辆信息
            
            FCVehicleIolAndCurveModel *model = self.carIDListArray[0];
            [self.vehicleBtn setTitle:model.CarNo forState:UIControlStateNormal];
            self.carID = model.CarID;
        }
        
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - 自定义时间选择
- (void)selectorDateButtonClick:(UIButton *)sender{
    
    //日期选择页面
    _calenderPicker= [SZCalendarPicker showOnView:kWindow];
    _calenderPicker.today = [NSDate date];
    _calenderPicker.date = [CommClass dateFormatTimeStamp:self.timeString timeFormat:NEW_TIME_FORMATTER_DATE];
    _calenderPicker.frame = CGRectMake(0, 0, kScreenWidth, 370);
    __weak typeof(self) weakSelf = self;
    //选择日期的回调函数
    _calenderPicker.calendarDateBlock = ^(NSDate * date){
        
        NSString *timeStr = [CommClass formatTimeStamp:date timeFormat:NEW_TIME_FORMATTER_DATE];
        
        weakSelf.timeString = timeStr;
        
        [sender setTitle:timeStr forState:UIControlStateNormal];
    };
}

#pragma mark - 打开选项框 关闭选项框
//打开选项框
- (void)showViewWithY:(CGFloat)y andHeight:(CGFloat)h andTag:(NSInteger)tag{

    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    [window addSubview:self.selectedBackView];
    _optionsTableView.frame = CGRectMake(10, y, kScreenWidth - 20, h);
    _optionsTableView.tag = tag;
}

//关闭选项框
-(void)closeOptionView{
    
    [self.selectedBackView removeFromSuperview];
}

//tap手势
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//判断如果点击的是tableView的cell，就把手势给关闭了
        
        return NO;//关闭手势
    }
    //否则手势存在
    return YES;
}

#pragma mark - 创建选择框
- (void)setUpSelectedOption{
    //选择车辆部门
    self.areaBtn = [self creartBtnWithTitle:@"选择车辆部门" andTag:100];
    self.areaBtn.frame = CGRectMake(10, 64 + 10, kScreenWidth - 20, 55);
    
    //选择车辆
    self.vehicleBtn = [self creartBtnWithTitle:@"选择车辆" andTag:101];
    self.vehicleBtn.frame = CGRectMake(10, CGRectGetMaxY(self.areaBtn.frame) + 10, kScreenWidth - 20, 55);
    
    //选择日期
    self.timeString = [CommClass formatTimeStamp:[NSDate date] timeFormat:NEW_TIME_FORMATTER_DATE];
    self.dateBtn = [self creartBtnWithTitle:self.timeString andTag:102];
    self.dateBtn.frame = CGRectMake(10, CGRectGetMaxY(self.vehicleBtn.frame) + 10, kScreenWidth - 20, 55);
    
    //开始时间
    //设置时间间隔（秒）
    NSTimeInterval beforeTime = - 50 * 60;//50分钟的秒数
    NSDate * beforeMinutes = [[NSDate date] dateByAddingTimeInterval:beforeTime];
    self.startStr = [CommClass formatTimeStamp:beforeMinutes timeFormat:TIME_FORMATTER_HM];
    self.startBtn = [self creartBtnWithTitle:self.startStr andTag:103];
    self.startBtn.frame = CGRectMake(10, CGRectGetMaxY(self.dateBtn.frame) + 10, (kScreenWidth - 50)/2, 55);
    
    //中间横线
    UIView *separatorViwe = [[UIView alloc]init];
    separatorViwe.backgroundColor = COLOR(13, 169, 215, 1);
    separatorViwe.frame = CGRectMake(CGRectGetMaxX(self.startBtn.frame)+10, CGRectGetMaxY(self.startBtn.frame)-27.5, 10, 1);
    [self.view addSubview:separatorViwe];
    
    //结束时间
    NSTimeInterval lastTime = 10 * 60;//10分钟的秒数
    NSDate * lastMinutes = [[NSDate date] dateByAddingTimeInterval:lastTime];
    self.endStr = [CommClass formatTimeStamp:lastMinutes timeFormat:TIME_FORMATTER_HM];
    self.endBtn = [self creartBtnWithTitle:self.endStr andTag:104];
    self.endBtn.frame = CGRectMake(10 + 30 + (kScreenWidth - 50)/2, CGRectGetMaxY(self.dateBtn.frame) + 10, (kScreenWidth - 50)/2, 55);
    
    //取消按钮
    UIButton *cancelBtn = [[UIButton alloc]init];
    cancelBtn.frame = CGRectMake(25, kScreenHeight - 65, (kScreenWidth - 75)/2, 50);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:COLOR(51, 51, 51, 1) forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    cancelBtn.layer.cornerRadius = 4.0f;
    cancelBtn.layer.masksToBounds = YES;
    cancelBtn.layer.borderWidth = 1.0f;
    cancelBtn.layer.borderColor = COLOR(121, 121, 121, 1).CGColor;
    [cancelBtn addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn];
    
    //确定按钮
    UIButton *commitBtn = [[UIButton alloc]init];
    commitBtn.frame = CGRectMake(50 + (kScreenWidth - 75)/2, kScreenHeight - 65, (kScreenWidth - 75)/2, 50);
    [commitBtn setTitle:@"确定" forState:UIControlStateNormal];
    [commitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [commitBtn setBackgroundColor:COLOR(22, 155, 213, 1)];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    commitBtn.layer.cornerRadius = 4.0f;
    commitBtn.layer.masksToBounds = YES;
    [commitBtn addTarget:self action:@selector(commitButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:commitBtn];
}

//自定义btn
- (FCCustomIolAndCurveButton *)creartBtnWithTitle:(NSString *)title andTag:(NSInteger)tag{
    
    FCCustomIolAndCurveButton *btn = [[FCCustomIolAndCurveButton alloc]init];
    [btn setTitle:title forState:UIControlStateNormal];
    btn.tag = tag;
    [btn addTarget:self action:@selector(selectedButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    return btn;
}
#pragma mark - 懒加载
- (FCVehicleIolAndCurveDakePickerView *)datePickerView{
    
    if (!_datePickerView) {
        
        _datePickerView = [[FCVehicleIolAndCurveDakePickerView alloc]init];
        _datePickerView.frame = [[UIScreen mainScreen] bounds];
        [_datePickerView setHidden:YES];
        
        __weak typeof(self) weakSelf = self;
        _datePickerView.timeWithHMCompletionHandle = ^(NSString *time, NSInteger tag){
            
            if (tag == 500) {//开始时间
                
                weakSelf.startStr = time;
                [weakSelf.startBtn setTitle:time forState:UIControlStateNormal];
            }
            else if (tag == 501){//结束时间
                
                weakSelf.endStr = time;
                [weakSelf.endBtn setTitle:time forState:UIControlStateNormal];
            }
        };
        [self.view addSubview:_datePickerView];
    }
    
    return _datePickerView;
}

- (UIView *)selectedBackView{
    
    if (!_selectedBackView) {
        
        _selectedBackView = [[UIView alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
//        _selectedBackView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeOptionView)];
        tap.delegate = self;
        [_selectedBackView addGestureRecognizer:tap];
        
        _optionsTableView = [[FCVehicleIolAndCurveOptionTableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
        _optionsTableView.layer.borderWidth = 1.0f;
        _optionsTableView.layer.borderColor = COLOR(13, 169, 215, 1).CGColor;
        [_selectedBackView addSubview:_optionsTableView];
        
        __weak typeof(self) weakSelf = self;
        
        _optionsTableView.selectedCompletionHandle = ^(NSString *type, NSString *paramID, NSString *paramName){
          
            if ([type isEqualToString:@"1"]) {
                
                [weakSelf getCarByDepartID:paramID];//车辆信息
                
                [weakSelf.areaBtn setTitle:paramName forState:UIControlStateNormal];
            }
            else{
                
                weakSelf.carID = paramID;
                
                [weakSelf.vehicleBtn setTitle:paramName forState:UIControlStateNormal];
            }
            
            [weakSelf closeOptionView];
        };
    }
    
    return _selectedBackView;
}

- (NSMutableArray *)departListArray{
    
    if (!_departListArray) {
        
        _departListArray = [NSMutableArray array];
    }
    
    return _departListArray;
}

- (NSMutableArray *)carIDListArray{
    
    if (!_carIDListArray) {
        
        _carIDListArray = [NSMutableArray array];
    }
    
    return _carIDListArray;
}

@end
